/**
 * Copyright ? 2015-2035 万雍科技 All Rights Reserved.  
 * File name:      RoleManageService.java
 * Date:           2015-12-21
 * Description:    角色管理
 * Modify History:     Date             Programmer       Notes
 *                    ---------        ---------------  ---------
 *                    2015-12-21        张旭星                           Initial
 **********************************************************************/
package com.wy.framework.services.permission;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.wy.framework.constants.Constants;
import com.wy.framework.constants.FieldConstant;
import com.wy.framework.constants.RtnCodeConstant;
import com.wy.framework.dao.ErrorSqlException;
import com.wy.framework.exceptions.ServiceException;
import com.wy.framework.pojos.TSysOrginfo;
import com.wy.framework.pojos.TSysOrgroles;
import com.wy.framework.pojos.TSysRoleinfo;
import com.wy.framework.pojos.TSysUserinfo;
import com.wy.framework.services.AbstractBaseService;
import com.wy.component.properties.PropertiesUtil;

@Service
public class RoleManageService extends AbstractBaseService {

    private static Logger logger = LoggerFactory.getLogger(RoleManageService.class);

    /**
     * 查询全部机构信息
     */
  /*  @SuppressWarnings({ "rawtypes", "unchecked" })
	public List<Map> queryRoleInfo(TSysOrginfo orgInfo) throws ServiceException {
	try {
	    List<Map> roleInfoMapList = new ArrayList<Map>();
	    // 查询机构信息
	    List param = new ArrayList();
	    param.add(orgInfo.getOrgCode());
//	    param.add(loginUser().getRoleId());
	    String replaceStr="";
	    if(StringUtils.equals(loginUser().getUserId(), "admin")){
	    	replaceStr= "or tr.roleId='"+new PropertiesUtil().getAppProperties("ROLE_YB_USER")+"'";
	    }
	    Map m = new HashMap();
		m.put("REPLACE_STR1",replaceStr);
	    List<Map> roleInfoList = dataBaseDao.queryForListReplaceStr("Tc_Sys_RoleInfo.queryRoleInfo",param,m);
	    for (Map roleInfo : roleInfoList) {
		Map temp = new HashMap();
		msgSourceAdapter.translateMap(roleInfo, FieldConstant.isAvailable);
		temp.put("roleInfo", roleInfo);
		roleInfoMapList.add(temp);
	    }
	    return roleInfoMapList;
	} catch (Exception e) {
	    logger.error("系统错误:{}", e);
	    // e.printStackTrace();
	    throw new ServiceException(e);
	}
  }*/

    /**
     * 新增机构信息
     * @param orgInfo 
     */
    public String saveRoleInfo(TSysRoleinfo roleInfo, TSysOrgroles orgRoles) throws ServiceException {
	try {
	    // 更新时间
	    roleInfo.flushUpdateTime();
	    roleInfo.setOperatorName("system");
	    roleInfo.setIsAvailable(Constants.IS_AVAILABLE);
	    roleInfo.setRoleId(UUID.randomUUID().toString());
	    logger.info("保存机构信息");
	    dataBaseDao.save(roleInfo);
		
	    orgRoles.setOrgRoleId(UUID.randomUUID().toString());
	    orgRoles.setRoleId(roleInfo.getRoleId());
	    orgRoles.setIsAvailable(Constants.IS_AVAILABLE);
	    orgRoles.setOperatorName("system");
	    orgRoles.flushUpdateTime();
	    dataBaseDao.save(orgRoles);
	    return RtnCodeConstant.RTN_CODE_SUCCESS;
	} catch (Exception e) {
	    logger.error("系统错误:{}", e);
	    // e.printStackTrace();
	    throw new ServiceException(e);
	}
   }

    /**
     * 更新机构信息
     * @param orgInfo 
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public String updateRoleInfo(TSysRoleinfo roleInfo) throws ServiceException {
		try {
			String roleId=ServletActionContext.getRequest().getParameter("roleId");
			String orgCode=ServletActionContext.getRequest().getParameter("orgCode");
			roleInfo.setRoleId(roleId);
			roleInfo.flushUpdateTime();
			roleInfo.setOperatorAccount(loginUser().getUserId());
			roleInfo.setOperatorName(loginUser().getUserName());
			dataBaseDao.update(roleInfo);
			List<Map> list =dataBaseDao.queryForList("t_sys_orgroles.query",roleId);
			TSysOrgroles tSysOrgroles=new TSysOrgroles();
			tSysOrgroles.setOrgRoleId((String)list.get(0).get("ORGROLEID"));
			tSysOrgroles.setRoleId(roleId);
			tSysOrgroles.setOrgCode(orgCode);
			tSysOrgroles.flushUpdateTime();
			tSysOrgroles.setOperatorAccount(loginUser().getUserId());
			tSysOrgroles.setOperatorName(loginUser().getUserName());
			tSysOrgroles.setIsAvailable(Constants.IS_AVAILABLE);
			dataBaseDao.getHibernateTemplate().update(tSysOrgroles);
		    return RtnCodeConstant.RTN_CODE_SUCCESS;
		} catch (Exception e) {
		    logger.error("系统错误:{}", e);
		    // e.printStackTrace();
		    throw new ServiceException(e);
		}
    }

    /**
     * 删除机构信息
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public String deleteRoleInfo(String roleId) throws ServiceException {
    	List params=new ArrayList();
		try {
			params.add(roleId);
			dataBaseDao.update("t_sys_roleinfo.delByRoleId",params);
			dataBaseDao.update("t_sys_orgroles.delByRoleId",params);
		    return RtnCodeConstant.RTN_CODE_SUCCESS;
		} catch (Exception e) {
		    logger.error("系统错误:{}", e);
		    return RtnCodeConstant.RTN_CODE_BEEN_USED;
		}
    }
    /**
     * 加载有效机构信息(供下拉选择)
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
	public List<Map> LoadRoleInfo(TSysUserinfo loginUser) throws ServiceException {
    	try {
    	    // 查询机构信息
    	    List param = new ArrayList();
    	    param.add(loginUser.getDept());
    	    List<Map> roleInfoList=null;
    	    if(StringUtils.equals(loginUser.getDept(), "000000")){
    	    	//超管(admin)查看二级管理员角色
    	    	param.add(loginUser.getDept());
    			roleInfoList = dataBaseDao.queryForList("TC_Sys_OrgInfo.loadRoleInfoByDept",param);
    	    }
    	    else{
    	    	//其它查看本身机构及子机构管理员
    	    	roleInfoList = dataBaseDao.queryForList("TC_Sys_OrgInfo.loadRoleInfo",param);
    	    }
    	    return roleInfoList;
    	} catch (Exception e) {
    	    logger.error("系统错误:{}", e);
    	    throw new ServiceException(e);
    	}
    }

	@SuppressWarnings({"unchecked","rawtypes"})
	public List<Map> loadRoleInfoForUser(String orgCode) throws ServiceException {
		List params=new ArrayList();
		try {
			params.add(orgCode);
	    	return dataBaseDao.queryForList("t_sys_orginfo.loadRoleInfoForUser",params);
    	} catch (Exception e) {
    	    logger.error("系统错误:{}", e);
    	    throw new ServiceException(e);
    	}
	}
	
	@SuppressWarnings({"unchecked","rawtypes"})
	public List<Map> loadUserByRoleId(String roleId) throws ServiceException {
		try {
    	    // 查询机构信息
    	    List<Map> roleInfoList=null;
	    	roleInfoList = dataBaseDao.queryForList("t_sys_roleinfo.loadRoleInfoByRoleId",roleId);
    	    return roleInfoList;
    	} catch (Exception e) {
    	    logger.error("系统错误:{}", e);
    	    // e.printStackTrace();
    	    throw new ServiceException(e);
    	}
	}

	@SuppressWarnings({"unchecked","rawtypes"})
	public List<Map> queryRoleInfo(String orgCode,String searchContent) throws ErrorSqlException {
		List<Map> roleInfoList=null;
		List params=new ArrayList();
		if(StringUtils.isEmpty(searchContent)){
			if(StringUtils.equals(orgCode, "000000")){
				roleInfoList  = dataBaseDao.queryForList("t_sys_roleinfo.queryAllRoleInfo");
			}else{
				roleInfoList  = dataBaseDao.queryForList("t_sys_roleinfo.queryroleinfo",orgCode);
			}
		}else{
			params.add(searchContent);
			params.add(searchContent);
			params.add(searchContent);
			roleInfoList  = dataBaseDao.queryForList("t_sys_roleinfo.queryRoleByContent",params);
		}
	 
	    return roleInfoList;
	}
	
}
